// Copyright 2022 jeff.li. and/or its affiliates.

#include <../src/codegen/codegen_c_host.h>
#include <gtest/gtest.h>
#include <tbir/ir/function.h>
#include <tbir/ir/module.h>
#include <tbir/ir/prim_builtin.h>
#include <tbir/ir/prim_expr.h>
#include <tbir/ir/tuple_expr.h>
#include <tbir/runtime/container.h>
#include <tbir/runtime/logging.h>
#include <tbir/runtime/registry.h>
#include <iostream>

namespace tbir::ir {
    using namespace runtime;

    TEST(IR, ListContainer) {
        const auto *printer = ::tbir::runtime::FunctionRegistry::Get("ir.AsText");
        ListType list_ty;

        auto list_append_op = Op::Get("ir.list_append");
        Constructor list_constructor(ListType(), "List", {}, GlobalTypeVar());
        Call call_list_init(list_ty, list_constructor, {InitializerList({StringImm("hello")})});

        AllocaVarStmt alloca_var("result", list_ty, call_list_init);
        Call call_list_append(list_ty, list_append_op, {alloca_var->var, StringImm("test")});
        ExprStmt es1(call_list_append);
        ReturnStmt ret_stmt(alloca_var->var);

        Array<Stmt> seqs;
        seqs.push_back(alloca_var);
        seqs.push_back(es1);
        seqs.push_back(ret_stmt);

        Function func({}, {}, SeqStmt(seqs), list_ty, {});
        String ir_text = (*printer)({func}).As<String>();

        func = WithAttr(std::move(func), attr::kGlobalSymbol, StringRef("return_list"));
        std::cout << ir_text << std::endl;

        codegen::CodeGenCHost cg;
        cg.AddFunction(func);
        std::string code = cg.Finish();
        std::cout << code << std::endl;
    }

}  // namespace tbir::ir
